<?php

namespace User;

use C\L\AdmController;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

class UserController extends AdmController
{
    protected function init()
    {
        $this->service = $this->s_user;
        $this->keyworkSearchKeys = [
            'name',
            'mobile',
            'nick_name'
        ];
        $this->hideKeys = [
            'passwd', 'pay_pwd', 'salt', 'is_delete'
        ];

        $this->timeToDateKeys = [
            'uptime', 'addtime', 'freeze_login_time', 'last_login_time'
        ];

        $this->updateKeys = [
            'name', 'tmobile', 'idcard',
            'passwd', 'pay_pwd',
            'mobile', 'is_auth', 'money', 'status', 'prize_num', 'nick_name',
            'note',
        ];

        $this->createKeys = [
            'name', 'tmobile', 'idcard', 'mobile',
            'passwd', 'pay_pwd', 'is_auth',
            'money', 'status', 'prize_num', 'nick_name',
            'note',
        ];
        $this->pubSearchKeys = [
            'status', 'is_auth', 'reg_ip', 'channel'
        ];
    }

    protected function beforeSearch()
    {
        $key = 'login_user';
        $this->cache->zRemRangeByScore($key, 0, time() - 180);
        $isOnline = $this->getValue('is_online', false);
        if ($isOnline) {
            $key = 'login_user';
            $uids = $this->cache->zRangeByScore($key, 0, time());
            if (!empty($uids)) {
                $this->params['data']['uid'] = $uids;
                $this->params['data_type']['uid'] = 'in';
            } else {
                $this->params['data']['uid'] = -1;
            }
        }


        $levelId = $this->getValue('level', true, 'int');
        if ($levelId > 0) {
            $scores = $this->s_level->getNextLevelScore($levelId);
            if ($scores[1] > 0) {
                $this->params['data']['credit'] = $scores;
                $this->params['data_type']['credit'] = 'between';
            } else {
                $this->params['data']['credit'] = $scores[0];
                $this->params['data_type']['credit'] = '>=';
            }
        }

        return true;
    }

    protected function afterSearch(&$data)
    {
        $key = 'login_user';
        foreach ($data['list'] as &$value) {
            $other = [
                'online_status' => $this->cache->zScore($key, $value['uid']) ? '在线' : '离线', //在线状态
                'top_mobile' => $this->s_user->getTopMobile($value['t_uid']), //推荐人手机号
                'user_level' => $this->s_level->getLevel($value['uid'])['name']
            ];
            $value = array_merge($value, $other);
        }
        $data['user_num'] = $this->s_user->getCount();
        $data['online_user_num'] = $this->cache->zCount($key, 0, time());

        $config = $this->s_user->getStatusConfig()['channel'];

        $channelInfo = [];
        $todayTime = strtotime(date('Ymd'));
        foreach ($config as $k => $v) {
            $count = $this->s_user->getCount(['channel' => $k]);
            $todayCount = $this->s_user->getCount(['channel' => $k, 'addtime' => $todayTime], ['addtime' => '>=']);
            $channelInfo[] = "{$v}：[总人数：$count, 今日注册人数：$todayCount]";
        }
        $data['channel_info'] = implode('，', $channelInfo);
        return true;
    }

    protected function afterView(&$data)
    {
        $data['view']['passwd'] = $data['view']['pay_pwd'] = null;
        $data['view']['tmobile'] = '';
        if ($data['view']['t_uid'] > 0) {
            $data['view']['tmobile'] = $this->s_user->getValue('mobile', $data['view']['t_uid']);
        }
        return true;
    }


    protected function beforeUpdate(&$data)
    {
        $user = $this->s_user->search(['mobile' => $data['mobile']]);
        if (empty($user)) {
            $this->error('账号不存在');
        }

        if (!empty($user) && $user['uid'] != $this->getValue('id')) {
            $this->error('当前手机号已存在');
        }

        // $user = $this->s_user->search(['nick_name' => $data['nick_name']]);
        // if (!empty($user) && $user['uid'] != $this->getValue('id')) {
        //     $this->error('当前账号已存在');
        // }

        if (!empty($data['passwd'])) {
            $data['passwd'] = md5($data['passwd'] . $user['salt']);
        }

        if (!empty($data['pay_pwd'])) {
            $data['pay_pwd'] = md5($data['pay_pwd'] . $user['salt']);
        }

        if (!empty($data['tmobile'])) {
            $user = $this->s_user->search(['mobile' => $data['tmobile']]);
            if (!empty($user)) {
                $data['t_uid'] = $user['uid'];
            }
        }

        unset($data['tmobile']);
        return true;
    }

    protected function beforeCreate(&$data)
    {
        $user = $this->s_user->search(['mobile' => $data['mobile']]);
        if (!empty($user)) {
            $this->error('会员已存在');
        }

        $data['salt'] = $this->public->getRandStr(10);
        $data['passwd'] = md5($data['passwd'] . $data['salt']);
        $data['pay_pwd'] = md5($data['pay_pwd'] . $data['salt']);
        $data['avatar'] = "/upload/avatar/" . rand(1, 38) . "@3x.png";

        return true;
    }

    private function rule()
    {

        if (empty($data['mobile'])) {
            $this->error('手机号必填');
        }

        if (empty($data['passwd'])) {
            $this->error('登录密码必填');
        }

        if (empty($data['pay_pwd'])) {
            $this->error('交易密码必填');
        }

        if (empty($data['nick_name'])) {
            $this->error('会员账号不能为空');
        }

        return true;
    }


    //冻结会员
    public function freezeAction()
    {
        $uid = $this->getValue('uid', false, 'int');
        $user = $this->service->search($uid);

        if (!empty($user)) {
            $this->cache->remove($this->cache->get('ssid_' . $uid));
            $this->service->update($uid, ['status' => 'N']);
        }

        $this->success();
    }

    //删除用户
    public function removeAction()
    {
        $uid = $this->getValue('uid', false, 'int');
        $user = $this->service->search($uid);

        if (!empty($user)) {
            $this->service->update($uid, ['is_delete' => 1]);
        }

        $this->success();
    }

    public function setMoneyAction()
    {
        $id     = $this->getValue('id', true, 'int');
        $money  = $this->getValue('money', true, 'float');
        $type   = $this->getValue('type', true) ?: 0;
        $remark = $this->getValue('remark', false, 'string');

        if ($this->s_user->setMoney($id, $remark, $money, $type, 'money', $remark)) {
            $this->success();
        }

        $this->error($this->message->getSerMsg());
    }

  /**
   * 物流信息用户搜索
   */
    public function selectUserAction()
    {
        $keyword = $this->getValue('keyword_search_value', false);
        $page_curren = $this->getValue('page_curren', false) ?? 1;
        $page_num = $this->getValue('page_num', false) ?? 10;
        $where = [
        'mobile' => "(uid = '{$keyword}' or mobile like '%{$keyword}%' or nick_name like '%{$keyword}%')"
        ];
        $alias = ['mobile' => 'sql'];
        $users = $this->s_user->searchPage(
            $where,
            $alias,
            ['uid', 'nick_name', 'name', 'mobile', 'credit', 'addtime'],
            '',
            $page_curren,
            $page_num
        );
        foreach ($users as &$value) {
            $value['address'] = $this->s_user_address->getAddress($value['uid']);
            $value['vip_name'] = $this->s_level->getLevel($value['uid'])['name'];
            $value['addtime_date'] = date('Y-m-d H:i:s', $value['addtime']);
        }
        $data = [
            'list' => $users,
            'count' => $this->service->getCount($where, $alias),
            'page_num' => $page_num,
            'page_curren' => $page_curren,
        ];
        $this->success($data);
    }

    //导出会员列表
    public function exportUserListAction()
    {
        if (empty($this->service)) {
            $this->error();
        }

        $this->params = [
            'data' => [],
            'data_type' => [],
            'columns' => [],
            'order' => '',
        ];

        $this->params['page_curren'] = 1;
        $this->params['page_num'] = 1000000;

        $this->setSearchParams();

        if (!$this->beforeSearch()) {
            $this->error('请求失败');
        }

        $data = empty($this->params['data']) ? [] : $this->params['data'];
        $dataType = empty($this->params['data_type']) ? [] : $this->params['data_type'];
        $columns = empty($this->params['columns']) ? [] : $this->params['columns'];
        $order = empty($this->params['order']) ? '' : $this->params['order'];

        $list = $this->service->searchPage(
            $data,
            $dataType,
            $columns,
            $order,
            $this->params['page_curren'],
            $this->params['page_num']
        );

        $this->setHide($list);
        $this->setShow($list);
        $this->setStatusName($list);
        $this->autoTimeToDate($list);


        $excelData = array_values($list);

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('phpspreadsheet');
        $spreadsheet->getActiveSheet()->setTitle('会员');
        $sheet->setCellValue('A1', 'ID');
        $sheet->setCellValue('B1', '姓名');
        $sheet->setCellValue('C1', '手机');
        $sheet->setCellValue('D1', '设备类型');

        $i = 2;
        foreach ($excelData as $d) {
            $sheet->setCellValue('A'.$i, $d['uid']);
            $sheet->setCellValue('B'.$i, $d['name']);
            $sheet->setCellValue('C'.$i, $d['mobile']);

            $phone_type = ($d['imei'] || $d['oaid']) ? '安卓' : '其他';
            $sheet->setCellValue('D'.$i, $phone_type);
            $i++;
        }

        $filename = 'members_' . time() . ".xlsx";
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        ob_start();
        $writer->save('php://output');
        $content = ob_get_clean();

        return $this->responseBinary([
            'filename'     => $filename,
            'content'      => $content,
            'content_type' => 'application/vnd.ms-excel'
        ]);
    }
}
